package cn.wmelon.shell.command.builder;

import cn.wmelon.shell.command.script.builder.ScriptBuilder;

/**
 * 组装 执行的命令 内容
 * 按照 链式顺序 执行
 *
 * @author watermelon
 * @time 2020/3/4
 */
public class CommandBuilder {



    /**
     * 两个命令的间隔
     */
    public static final String SPILT = ";";

    private StringBuilder stringBuilder = new StringBuilder();


    /**
     * 创建一个脚本文件
     *
     * @param script
     * @return
     */
    public CommandBuilder createScript(ScriptBuilder script) {
        this.stringBuilder.append(script.build() + SPILT);
        return this;
    }


    /**
     * 赋予脚本可执行权限
     *
     * @param script 脚本对象
     * @return
     */
    public CommandBuilder chmodXScript(ScriptBuilder script) {
        this.stringBuilder.append("chmod +x ");
        this.stringBuilder.append(script.getFilePath() + SPILT);
        return this;
    }

    /**
     * 赋予脚本可执行权限
     *
     * @param scriptPath 脚本绝对地址
     * @return
     */
    public CommandBuilder chmodXScript(String scriptPath) {
        this.stringBuilder.append("chmod +x ");
        this.stringBuilder.append(scriptPath + SPILT);
        return this;
    }

    /**
     * 执行一个脚本
     *
     * @param script 脚本对象
     * @return
     */
    public CommandBuilder execScript(ScriptBuilder script) {
        this.stringBuilder.append("sh ");
        this.stringBuilder.append(script.getFilePath() + SPILT);
        return this;
    }


    /**
     * 执行一个脚本
     *
     * @param scriptPath 脚本绝对地址
     * @return
     */
    public CommandBuilder execScript(String scriptPath) {
        this.stringBuilder.append("sh ");
        this.stringBuilder.append(scriptPath + SPILT);
        return this;
    }


    /**
     * 删除一个脚本
     *
     * @param script 脚本对象
     * @return
     */
    public CommandBuilder delScript(ScriptBuilder script) {
        this.stringBuilder.append("rm -rf ");
        this.stringBuilder.append(script.getFilePath() + SPILT);
        return this;
    }


    /**
     * 删除一个脚本
     *
     * @param scriptPath 脚本绝对地址
     * @return
     */
    public CommandBuilder delScript(String scriptPath) {
        this.stringBuilder.append("rm -rf ");
        this.stringBuilder.append(scriptPath + SPILT);
        return this;
    }

    /**
     * 新增 -> 赋予权限 -> 执行 -> 删除 一条龙
     *
     * @param script 脚本对象
     * @return
     */
    public CommandBuilder aDragon(ScriptBuilder script) {
        this.createScript(script)
                .chmodXScript(script)
                .execScript(script)
                .delScript(script);
        return this;
    }

    /**
     * 增加命令
     *
     * @param line
     * @return
     */
    public CommandBuilder addOne(String line) {
        this.stringBuilder.append(line + SPILT);
        return this;
    }

    /**
     * 获取最终可以执行的命令
     *
     * @return
     */
    public String build() {
        return stringBuilder.toString();
    }
}
